package mn.slide.laborberlin.adaptor;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import mn.slide.laborberlin.db.DataLayer;
import mn.slide.laborberlin.db.DatabaseManager;
import mn.slide.laborberlin.main.DetialActivity;
import mn.slide.laborberlin.main.R;
import mn.slide.laborberlin.main.UeberSchriftActivity;
import mn.slide.laborberlin.model.EntragData;
import mn.slide.laborberlin.model.Kapitel;
import mn.slide.laborberlin.model.SubUeberSchrift;
import mn.slide.laborberlin.model.UeberBase;
import mn.slide.laborberlin.model.UeberSchrift;
import mn.slide.laborberlin.model.UnterSuchung;
import mn.slide.laborberlin.tabgroup.HomeGroupActivity;
import android.app.Activity;
import android.content.Intent;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

public class EinExtendableAdapter extends BaseExpandableListAdapter implements
		SectionIndexer {

	private Activity myContext;

	private List<EntragData> item;
	HashMap<String, List<EntragData>> alphaIndexer;
	HashMap<String, Integer> index;
	String[] sections;
	CharsetDecoder decoderDestino;
	Charset charsetDestino;
	CharsetEncoder encoderOrigem;
	Charset charsetOrigem;
	int typePosition;
	String desc;

	public EinExtendableAdapter(Activity context, int position) {
		myContext = context;
		this.typePosition = position;
		this.item = DataLayer.layer.getUnterSuchung(position);
		if (this.item != null) {
			Collections.sort(item, new Comparator<EntragData>() {
				public int compare(EntragData e1, EntragData e2) {
					return e1.getName().toUpperCase()
							.compareTo(e2.getName().toUpperCase());
				}
			});
		}

		charsetDestino = Charset.forName("ISO-8859-1");
		decoderDestino = charsetDestino.newDecoder();
		charsetOrigem = Charset.forName("ISO-8859-1");
		encoderOrigem = charsetOrigem.newEncoder();

		alphaIndexer = new HashMap<String, List<EntragData>>();
		index = new HashMap<String, Integer>();
		int size = item.size();
		Log.v("Size", size + " ");
		int i = 0;
		for (EntragData s : item) {

			// get the first letter of the store

			if (s != null) {
				String ch = s.getName().substring(0, 1);
				// convert to uppercase otherwise lowercase a -z will be sorted
				// after upper A-Z
				ch = ch.toUpperCase();
				if (ch.equalsIgnoreCase("SS")) {
					ch = myContext.getString(R.string.ss);
				} else if (ch.equalsIgnoreCase("UE")) {
					ch = myContext.getString(R.string.ue);
				} else if (ch.equalsIgnoreCase("OE")) {
					ch = myContext.getString(R.string.oe);
				} else if (ch.equalsIgnoreCase("AE")) {
					ch = myContext.getString(R.string.ae);
				}
				Log.v("Name", s.getName());
				// HashMap will prevent duplicates
				if (alphaIndexer.containsKey(ch)) {
					alphaIndexer.get(ch).add(s);
				} else {
					List<EntragData> list = new ArrayList<EntragData>();
					list.add(s);
					alphaIndexer.put(ch, list);
				}
				index.put(ch, i);
				i++;
			}
		}

		Set<String> sectionLetters = alphaIndexer.keySet();

		// create a list from the set to sort
		ArrayList<String> sectionList = new ArrayList<String>(sectionLetters);

		Collections.sort(sectionList);

		sections = new String[sectionList.size()];

		sectionList.toArray(sections);
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return null;
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return 0;
	}

	@Override
	public View getChildView(int groupPosition, final int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {

		View rowView = convertView;
		final ViewHolderChild child;
		if (rowView == null) {
			LayoutInflater inflate = myContext.getLayoutInflater();
			rowView = inflate.inflate(R.layout.list_item_middle, null, true);
			child = new ViewHolderChild();
			child.name = (TextView) rowView.findViewById(R.id.title);
			child.detials = (TextView) rowView.findViewById(R.id.subtitle);
			child.arrow = (ImageView) rowView.findViewById(R.id.chevron);
			rowView.setTag(child);
		} else {
			child = (ViewHolderChild) rowView.getTag();
		}
		final EntragData data = alphaIndexer.get(sections[groupPosition]).get(
				childPosition);
		if (data instanceof UnterSuchung) {
			final UnterSuchung unter = (UnterSuchung) data;
			rowView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(myContext, DetialActivity.class);
					DataLayer.layer.setUnter(unter);
					HomeGroupActivity.group.goTo(intent);

				}
			});
			if (typePosition != -1) {
				if (((UnterSuchung) data).getEntrag() != null) {
					Kapitel kapi = DataLayer.layer
							.getKapitelWithId(((UnterSuchung) data).getEntrag()
									.getKapitel().getId());
					desc = kapi.getValue();

					child.detials.setText(Html.fromHtml(desc));
				} else if (((UnterSuchung) data).getUeberSchrift() != null) {
					UeberSchrift ueber = ((UnterSuchung) data)
							.getUeberSchrift();
					desc = DataLayer.layer.getUeberSchriftWithId(ueber.getId())
							.getName();
					Kapitel kapi = DataLayer.layer.getKapitelWithId(ueber
							.getEintrag().getKapitel().getId());
					desc = kapi.getValue() + " -> " + desc;

					child.detials.setText(Html.fromHtml(desc));
				} else if (((UnterSuchung) data).getSubUeberSchrift() != null) {
					SubUeberSchrift subUeber = ((UnterSuchung) data)
							.getSubUeberSchrift();
					desc = DataLayer.layer.getSubUeberSchriftWithId(
							subUeber.getId()).getName();
					UeberSchrift ueber = subUeber.getUeberSchrift();
					desc = DataLayer.layer.getUeberSchriftWithId(ueber.getId())
							.getName() + " -> " + desc;
					Kapitel kapi = DataLayer.layer.getKapitelWithId(ueber
							.getEintrag().getKapitel().getId());
					desc = kapi.getValue() + " -> " + desc;
				}
			}
			child.arrow.setVisibility(View.INVISIBLE);
		} else {
			child.arrow.setVisibility(View.VISIBLE);
			rowView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(myContext,
							UeberSchriftActivity.class);
					intent.putExtra("ueber", (UeberBase) data);
					HomeGroupActivity.group.goTo(intent);
				}
			});
			if (data instanceof UeberSchrift) {
				if (typePosition == -1) {

					Kapitel kapi = DataLayer.layer
							.getKapitelWithId(((UeberSchrift) data)
									.getEintrag().getKapitel().getId());
					if (desc != null) {
						desc = kapi.getValue() + " -> " + desc;
					} else {
						desc = kapi.getValue();
					}
					child.detials.setText(Html.fromHtml(desc));
					child.detials.setVisibility(View.VISIBLE);
				}
			} else {
				if (typePosition == -1) {
					desc = ((SubUeberSchrift) data).getUeberSchrift().getName();
					Kapitel kapi = DataLayer.layer
							.getKapitelWithId(((SubUeberSchrift) data)
									.getUeberSchrift().getEintrag()
									.getKapitel().getId());
					if (desc != null) {
						desc = kapi.getValue() + " -> " + desc;
					} else {
						desc = kapi.getValue();
					}
					child.detials.setText(Html.fromHtml(desc));
					child.detials.setVisibility(View.VISIBLE);
				}
			}
		}
		if (typePosition != -1) {
			child.name.setText(Html.fromHtml(data.getName()));
			if (data.getBemerkungLv() != null) {
				child.detials.setText(Html.fromHtml(data.getBemerkungLv()));
				child.detials.setVisibility(View.VISIBLE);
			} else {
				child.detials.setVisibility(View.GONE);
			}
			if (childPosition == item.size() - 1)
				rowView.setVisibility(View.GONE);
		} else {
			child.name.setText(Html.fromHtml(data.getName()));
		}
		return rowView;
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		return alphaIndexer.get(sections[groupPosition]).size();
	}

	@Override
	public Object getGroup(int groupPosition) {
		return null;
	}

	@Override
	public int getGroupCount() {
		return sections.length;
	}

	@Override
	public long getGroupId(int groupPosition) {
		return 0;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {

		View rowView = convertView;
		final ViewHolderGroup group;
		if (rowView == null) {
			LayoutInflater inflate = myContext.getLayoutInflater();
			rowView = inflate.inflate(R.layout.ein_group_row, null, true);
			group = new ViewHolderGroup();
			group.arrow = (ImageView) rowView.findViewById(R.id.arrow);
			group.section = (TextView) rowView.findViewById(R.id.tvGroupName);
			rowView.setTag(group);
		} else {
			group = (ViewHolderGroup) rowView.getTag();
		}

		group.section.setText(sections[groupPosition]);
		if (isExpanded) {
			group.arrow.setImageResource(R.drawable.carat_open);
		} else {
			group.arrow.setImageResource(R.drawable.carat_close);
		}
		return rowView;
	}

	@Override
	public boolean hasStableIds() {
		return false;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

	@Override
	public int getPositionForSection(int section) {
		return index.get(sections[section]);
	}

	@Override
	public int getSectionForPosition(int position) {
		// TODO Auto-generated method stub
		return 1;
	}

	@Override
	public Object[] getSections() {
		return sections;
	}

	static class ViewHolderChild {
		protected TextView name;
		protected TextView detials;
		protected ImageView arrow;
	}

	static class ViewHolderGroup {
		protected ImageView arrow;
		protected TextView section;
	}
}
